package com.aqie.medium.design;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 341 设计一个迭代器，使其能够遍历这个整型列表中的所有整数
 * todo
 */
public class NestedIterator implements Iterator<Integer> {

    LinkedList<Iterator<NestedInteger>> stack = null;  //栈
    Integer num = null;
    boolean flag = false;

    public NestedIterator(List<NestedInteger> nestedList) {
        stack = new LinkedList<Iterator<NestedInteger>>();
        stack.addFirst(nestedList.iterator());
    }

    @Override
    public Integer next() {
        flag = false;
        return num;

    }

    @Override
    public boolean hasNext() {
        while(stack.size() > 0 && !flag){
            Iterator<NestedInteger> temp = stack.peekFirst();
            if(!temp.hasNext()){  // 遍历完了
                stack.removeFirst();
            }else{
                NestedInteger tt = temp.next();
                if(!tt.isInteger()){
                    stack.addFirst(tt.getList().iterator());
                    temp.remove();
                }else{
                    num = tt.getInteger();
                    flag = true;
                    temp.remove();
                }
            }
        }
        return flag;


    }
}
